package com.dd.lnetwork.provider

import android.content.Context
import com.dd.lnetwork.provider.ProviderMap.providerClassMap
import com.dd.lnetwork.provider.ProviderMap.providerMap

object ProviderProxy {

    /**
     * 从缓存中拿出provider
     * 没有则实例化对象
     *
     * @param cls
     * @param context
     * @param <T>
     * @return
    </T> */
    fun <T : IProvider> getProvider(
        cls: Class<T>, context: Context, deviceId: String,
        token: String?,
        cookies: HashSet<String>?
    ): T {
        val clsName = cls.name
        val provider = providerMap[clsName] ?: run {
            try {
                val providerCls: Class<out IProvider> = providerClassMap[clsName]!!
                val p = providerCls.getConstructor().newInstance()
                p.initClass(context, deviceId, token, cookies)
                p
            } catch (e: Exception) {
                throw ProviderException("Init provider failed! " + e.message)
            }
        }
        providerMap[cls.name] = provider
        return provider as T
    }

    /**
     * 缓存 provider 实现
     *
     * @param provider
     * @param providerImp
     * @param <T>
     * @param <K>
    </K></T> */
    fun <T : IProvider, K : T> addProvider(provider: Class<T>, providerImp: Class<K>) {
        providerClassMap[provider.name] = providerImp
    }
}